package cn.mesmile.amqp.demo.direct;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Recv1 {

    private final static String EXCHANGE_NAME = "exchange_direct";

    public static void main(String[] argv) throws Exception {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("81.69.43.78");
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/dev");
        factory.setPort(5672);

        //消费者一般不增加自动关闭
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME,BuiltinExchangeType.DIRECT);

        // 限制消费者每次只能处理一条消息，处理完成后才可以处理下一条
        channel.basicQos(1);

        String queueName = channel.queueDeclare().getQueue();

        // 队列绑定交换机
        channel.queueBind(queueName,EXCHANGE_NAME,"errorRouteKey");
        channel.queueBind(queueName,EXCHANGE_NAME,"infoRouteKey");
        channel.queueBind(queueName,EXCHANGE_NAME,"debugRouteKey");

        //回调方法，下面两种都行
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // consumerTag 是固定的 可以做此会话的名字， deliveryTag 每次接收消息+1
                System.out.println("consumerTag消息标识=" + consumerTag);
                //可以获取交换机，路由健等
                System.out.println("envelope元数据=" + envelope);

                System.out.println("properties配置信息=" + properties);

                System.out.println("body=" + new String(body, "utf-8"));


                //手工确认消息消费，不是多条确认
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        // ack 自从确认，实际生产环境 关闭自动确认
        channel.basicConsume(queueName, false, consumer);

//        DeliverCallback deliverCallback = (consumerTag, envelop, delivery,properties, msg) -> {
//            String message = new String(msg, "UTF-8");
//            System.out.println(" [x] Received '" + message + "'");
//        };

        //自动确认消息
        //channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
    }

}